package com.xzs.kit.base.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @Description 日期工具类
 * @author: Victor.Xiao
 **/
public class DateUtil {

	// private long lNow = System.currentTimeMillis();
	// private Calendar cNow = Calendar.getInstance();
	// private Date dNow = new Date(lNow);
	// private Timestamp tNow = new Timestamp(lNow);
	// private java.sql.Date today = new java.sql.Date(lNow);
	// private java.sql.Time now = new java.sql.Time(lNow);

	/**
	 * 默认构造方法
	 */
	public DateUtil() {

	}

	public static Timestamp getCurTime() {
		return new Timestamp(System.currentTimeMillis());
	}
	/*
	 * private DateTime(long lNow, Calendar cNow, Date dNow, Timestamp tNow,
	 * java.sql.Date today, Time now) { this.lNow = lNow; this.cNow = cNow;
	 * this.dNow = dNow; this.tNow = tNow; this.today = today; this.now = now; }
	 */

	/**
	 * 得到年
	 * 
	 * @param c
	 * @return
	 */
	public static int getYear(Calendar c) {
		if (c != null) {
			return c.get(Calendar.YEAR);
		} else {
			return Calendar.getInstance().get(Calendar.YEAR);
		}
	}

	/**
	 * 得到月份 注意，这里的月份依然是从0开始的
	 * 
	 * @param c
	 * @return
	 */
	public static int getMonth(Calendar c) {
		if (c != null) {
			return c.get(Calendar.MONTH);
		} else {
			return Calendar.getInstance().get(Calendar.MONTH);
		}
	}

	public static java.sql.Date getSqlDate() {
		return new java.sql.Date(System.currentTimeMillis());
	}

	/**
	 * 得到日期
	 * 
	 * @param c
	 * @return
	 */
	public static int getDate(Calendar c) {
		if (c != null) {
			return c.get(Calendar.DATE);
		} else {
			return Calendar.getInstance().get(Calendar.DATE);
		}
	}

	/**
	 * 得到星期
	 * 
	 * @param c
	 * @return
	 */
	public static int getDay(Calendar c) {
		if (c != null) {
			return c.get(Calendar.DAY_OF_WEEK);
		} else {
			return Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
		}
	}

	/**
	 * 得到小时
	 * 
	 * @param c
	 * @return
	 */
	public static int getHour(Calendar c) {
		if (c != null) {
			return c.get(Calendar.HOUR);
		} else {
			return Calendar.getInstance().get(Calendar.HOUR);
		}
	}

	/**
	 * 得到分钟
	 * 
	 * @param c
	 * @return
	 */
	public static int getMinute(Calendar c) {
		if (c != null) {
			return c.get(Calendar.MINUTE);
		} else {
			return Calendar.getInstance().get(Calendar.MINUTE);
		}
	}

	/**
	 * 得到秒
	 * 
	 * @param c
	 * @return
	 */
	public static int getSecond(Calendar c) {
		if (c != null) {
			return c.get(Calendar.SECOND);
		} else {
			return Calendar.getInstance().get(Calendar.SECOND);
		}
	}

	/**
	 * 得到指定或者当前时间前n天的Calendar
	 * 
	 * @param c
	 * @param n
	 * @return
	 */
	public static Calendar beforeNDays(Calendar c, int n) {
		// 偏移量，给定n天的毫秒数
		long offset = n * 24 * 60 * 60 * 1000;
		Calendar calendar = null;
		if (c != null) {
			calendar = c;
		} else {
			calendar = Calendar.getInstance();
		}

		calendar.setTimeInMillis(calendar.getTimeInMillis() - offset);
		return calendar;
	}

	/**
	 * 得到指定或者当前时间后n天的Calendar
	 * 
	 * @param c
	 * @param n
	 * @return
	 */
	public static Calendar afterNDays(Calendar c, int n) {
		// 偏移量，给定n天的毫秒数
		long offset = n * 24 * 60 * 60 * 1000;
		Calendar calendar = null;
		if (c != null) {
			calendar = c;
		} else {
			calendar = Calendar.getInstance();
		}

		calendar.setTimeInMillis(calendar.getTimeInMillis() + offset);
		return calendar;
	}

	/**
	 * 昨天
	 * 
	 * @param c
	 * @return
	 */
	public static Calendar yesterday(Calendar c) {
		long offset = 1 * 24 * 60 * 60 * 1000;
		Calendar calendar = null;
		if (c != null) {
			calendar = c;
		} else {
			calendar = Calendar.getInstance();
		}

		calendar.setTimeInMillis(calendar.getTimeInMillis() - offset);
		return calendar;
	}

	/**
	 * 明天
	 * 
	 * @param c
	 * @return
	 */
	public static Calendar tomorrow(Calendar c) {
		long offset = 1 * 24 * 60 * 60 * 1000;
		Calendar calendar = null;
		if (c != null) {
			calendar = c;
		} else {
			calendar = Calendar.getInstance();
		}

		calendar.setTimeInMillis(calendar.getTimeInMillis() + offset);
		return calendar;
	}

	/**
	 * 得到指定或者当前时间前offset毫秒的Calendar
	 * 
	 * @param c
	 * @param offset
	 * @return
	 */
	public static Calendar before(Calendar c, long offset) {
		Calendar calendar = null;
		if (c != null) {
			calendar = c;
		} else {
			calendar = Calendar.getInstance();
		}

		calendar.setTimeInMillis(calendar.getTimeInMillis() - offset);
		return calendar;
	}

	/**
	 * 
	 * @param date
	 * @param field
	 *            the calendar field.
	 * @param amount
	 *            the amount of date or time to be added to the field.
	 * @return
	 */
	public static Date add(Date date, int field, int amount) {
		if (date == null) {
			date = new Date();
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(field, amount);

		return calendar.getTime();
	}

	/**
	 * 得到指定或者当前时间前offset毫秒的Calendar
	 * 
	 * @param c
	 * @param offset
	 * @return
	 */
	public static Calendar after(Calendar c, long offset) {
		Calendar calendar = null;
		if (c != null) {
			calendar = c;
		} else {
			calendar = Calendar.getInstance();
		}

		calendar.setTimeInMillis(calendar.getTimeInMillis() - offset);
		return calendar;
	}

	/**
	 * 日期格式化
	 * 
	 * @param c
	 * @param pattern
	 * @return
	 */
	public static String format(Calendar c, String pattern) {
		Calendar calendar = null;
		if (c != null) {
			calendar = c;
		} else {
			calendar = Calendar.getInstance();
		}
		if (pattern == null || pattern.equals("")) {
			pattern = "yyyy年MM月dd日 HH:mm:ss";
		}
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);

		return sdf.format(calendar.getTime());
	}

	/**
	 * Date类型转换到Calendar类型
	 * 
	 * @param d
	 * @return
	 */
	public static Calendar Date2Calendar(Date d) {
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		return c;
	}

	/**
	 * Calendar类型转换到Date类型
	 * 
	 * @param c
	 * @return
	 */
	public static Date Calendar2Date(Calendar c) {
		return c.getTime();
	}

	/**
	 * Date类型转换到Timestamp类型
	 * 
	 * @param d
	 * @return
	 */
	public static Timestamp Date2Timestamp(Date d) {
		return new Timestamp(d.getTime());
	}

	/**
	 * Calendar类型转换到Timestamp类型
	 * 
	 * @param c
	 * @return
	 */
	public static Timestamp Calendar2Timestamp(Calendar c) {
		return new Timestamp(c.getTimeInMillis());
	}

	/**
	 * Timestamp类型转换到Calendar类型
	 * 
	 * @param ts
	 * @return
	 */
	public static Calendar Timestamp2Calendar(Timestamp ts) {
		Calendar c = Calendar.getInstance();
		c.setTime(ts);
		return c;
	}

	/**
	 * 得到当前时间的字符串表示 格式2010-02-02 12:12:12
	 * 
	 * @return
	 */
	public static String getTimeString() {
		return format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 标准日期格式字符串解析成Calendar对象
	 * 
	 * @param s
	 * @return
	 */
	public static Calendar pars2Calender(String s) {
		Timestamp ts = Timestamp.valueOf(s);
		return Timestamp2Calendar(ts);
	}

	public static boolean isToday(String day) {
		Date d, today;
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		try {
			d = dateFormat.parse(day);
			today = dateFormat.parse(dateFormat.format(new Date()));
			return today.compareTo(d) == 0 ? true : false;
		} catch (ParseException e) {
		}
		return false;
	}

	/**
	 * 判断时候当前是否在这个时间段内
	 */
	public static boolean isInTime(String beginTime, String endTime) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		return isInTime(dateFormat.format(new Date()), beginTime, endTime);
	}

	/**
	 * 判断时候当前是否在这个时间段内
	 *
	 */
	public static boolean isInTime(String day, String beginTime, String endTime) {
		Date dateBegin, dateEnd, now;
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			now = new Date();
			dateBegin = dateFormat.parse(day + " " + beginTime);
			dateEnd = dateFormat.parse(day + " " + endTime);
			return (now.after(dateBegin) && now.before(dateEnd));
		} catch (ParseException e) {
		}
		return false;
	}

	/**
	 * 判断时候当前是否在这个时间段内
	 * 
	 * @return
	 */
	public static boolean isAfter(String d) {
		Date date, now;
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			now = new Date();
			date = dateFormat.parse(d);
			return (now.after(date));
		} catch (ParseException e) {
		}
		return false;
	}

	/**
	 * 判断时候当前是否在这个时间段内
	 * 
	 * @return
	 */
	public static boolean isInDate(String begin, String end) {
		Date dateBegin, dateEnd, now;
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			now = new Date();
			dateBegin = dateFormat.parse(begin);
			dateEnd = dateFormat.parse(end);
			return (now.after(dateBegin) && now.before(dateEnd));
		} catch (ParseException e) {
		}
		return false;
	}

	/**
	 * @param args
	 */
	/*
	 * public static void main(String[] args) {
	 * System.out.println(isInTime("2010-12-8", "10:23:00", "10:40:00")); }
	 */

	/** 日期格式 yyyyMMdd **/
	public static final String YYYYMMDD = "yyyyMMdd";

	/** 日期格式 yyyy-MM-dd **/
	public static final String YYYY_MM_DD = "yyyy-MM-dd";

	/** 日期格式 yyyy-MM-dd HH:mm:ss **/
	public static final String YYYY_MM_DD_HH_MM_SS = YYYY_MM_DD + " HH:mm:ss";

	/** 日期格式 yyyyMMddHHmmss **/
	public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

	/** 日期格式 yyyyMMddHHmm **/
	public static final String YYYYMMDDHHMM = "yyyyMMddHHmm";

	/**
	 * 得到当前日期如果参数为空返回yyyy-MM-dd
	 * 
	 * @param pattern
	 *            格式化格式
	 * @return
	 */
	public static String formatDate(String pattern) {
		DateFormat simpleDateFormat = new SimpleDateFormat(pattern == null ? YYYY_MM_DD : pattern);
		String sdate = simpleDateFormat.format(new Date(System.currentTimeMillis()));
		return sdate;
	}

	/**
	 * 得到当前日期如果参数为空返回yyyy-MM-dd
	 * 
	 * @param date
	 * @param pattern
	 *            格式化格式
	 * @return
	 */
	public static String formatDate(Date date, String pattern) {
		DateFormat simpleDateFormat = new SimpleDateFormat(pattern == null ? YYYY_MM_DD : pattern);
		String sdate = simpleDateFormat.format(date == null ? new Date() : date);
		return sdate;
	}

	/**
	 * 得到日期中的天
	 * 
	 * @param date
	 * @return 1-日期中最后一天
	 */
	public static int getYear(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date == null ? calendar.getTime() : date);
		int year = calendar.get(Calendar.YEAR);
		return year;
	}

	/**
	 * 得到日期中的天
	 * 
	 * @param date
	 * @return 1-日期中最后一天
	 */
	public static int getDay(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date == null ? calendar.getTime() : date);
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		return day;
	}

	/**
	 * 得到日期中的月
	 * 
	 * @param date
	 * @return 1-12
	 */
	public static int getMonth(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date == null ? new Date() : date);
		return calendar.get(Calendar.MONTH) + 1;
	}

	/**
	 * 得到日期中的小时
	 * 
	 * @param date
	 * @return 0-23
	 */
	public static int getHour(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date == null ? new Date() : date);
		return calendar.get(Calendar.HOUR_OF_DAY);
	}

	public static int getMinu(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date == null ? new Date() : date);
		return calendar.get(Calendar.MINUTE);
	}

	public static int getSecond(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date == null ? new Date() : date);
		return calendar.get(Calendar.SECOND);
	}

	/**
	 * 得到日期中日期为周几
	 * 
	 * @param date
	 * @return 1-7(周一-周日)
	 */
	public static int getWeek(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date == null ? new Date() : date);
		int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
		return week == 0 ? 7 : week;
	}

	/**
	 * 根据日期获得所在周的日期
	 * 
	 * @param mdate mdate
	 * @return
	 */
	public static List<String> dateToWeek(Date mdate) {
		List<String> list = new ArrayList();
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(mdate);
		calendar.setFirstDayOfWeek(Calendar.MONDAY);
		calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		list.add(date2String(calendar.getTime(), YYYY_MM_DD));
		while (list.size() < 7) {
			calendar.add(Calendar.DAY_OF_MONTH, 1);
			list.add(date2String(calendar.getTime(), YYYY_MM_DD));
		}
		return list;
	}

	/**
	 * 将一个日期数据转换成整型
	 * 
	 * @param date
	 *            日期 2011-01-12
	 * @return 2011011312
	 */
	public static int dateToInt(Date date) {
		return (int) dateToLong(formatDate(date, YYYY_MM_DD));
	}

	/**
	 * 将一个日期数据转换成整型
	 * 
	 * @param date
	 *            日期 2011-01-12
	 * @return 2011011312
	 */
	public static int dateToInt(String date) {
		return dateToInt(parseDate(date, YYYY_MM_DD));
	}

	/**
	 * 将一个日期数据转换成整型
	 * 
	 * @param date
	 *            日期 2011-01-12 12:33:12 233
	 * @return 20110113123312233
	 */
	public static long dateToLong(String date) {
		long rs = 0;
		try {
			rs = Long.parseLong(date.replaceAll("[^\\d]", ""));
		} catch (Exception e) {
		}
		return rs;
	}

	/**
	 * 将一个日期数据转换成整型
	 * 
	 * @param date
	 *            日期 2011-01-12 12:33:12 233
	 * @return 20110113123312233
	 */
	public static long dateToLong(Date date) {
		long rs = 0;
		try {
			rs = Long.parseLong(formatDate(date, YYYYMMDDHHMMSS + "S"));
		} catch (Exception e) {
		}
		return rs;
	}

	/**
	 * 得到月中最后一天
	 * 
	 * @param date
	 * @return
	 */
	public static int getMontyLastDay(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date == null ? calendar.getTime() : date);
		return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
	}

	/**
	 * 将指定字符日期转日期对象
	 * 
	 * @param pattern
	 *            格式化格式默认为(yyyy-MM-dd)
	 * @param date
	 *            日期为空当前日期
	 * @return
	 */
	public static Date parseDate(String date, String pattern) {
		DateFormat df = new SimpleDateFormat(pattern == null ? YYYY_MM_DD : pattern);
		try {
			return df.parse(date == null ? formatDate(new Date(), pattern) : date);
		} catch (ParseException e) {
			return new Date();
		}
	}

	/**
	 * 将指定日期转成java.sql.Date对象
	 * 
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static java.sql.Date parseSqlDate(String date, String pattern) {
		return new java.sql.Date(parseDate(date, pattern).getTime());
	}

	/**
	 * 得到开始和结束日期指定周的月天(MMdd)
	 * 
	 * @param begin
	 *            开始日期(yyyy-MM-dd)
	 * @param end
	 *            结束日期(yyyy-MM-dd)
	 * @param weeks
	 *            周(1-7)
	 * @return 如(2011-05-21,2011-05-30,{1,2})返回:0523,0524,0530
	 */
	public static String getSpecWeekMMdd(Date begin, Date end, int[] weeks) {
		if (begin == null || end == null || weeks == null || weeks.length == 0) {
			return null;
		}
		Calendar beginc = Calendar.getInstance();
		beginc.setTime(begin);

		Calendar endc = Calendar.getInstance();
		endc.setTime(end);

		StringBuffer mds = new StringBuffer();
		while (beginc.compareTo(endc) <= 0) {
			int week = getWeek(beginc.getTime());
			for (int iweek : weeks) {
				if (week == iweek) {
					String md = DateUtil.formatDate(beginc.getTime(), "MMdd");
					mds.append(md).append(",");
				}
			}
			beginc.add(Calendar.DATE, 1);
		}
		if (mds.length() != 0) {
			mds.delete(mds.length() - 1, mds.length());
		}
		return mds.toString();
	}

	/**
	 * 跟据指定日期生成一个日期表 如2011-05
	 * <table border='1'>
	 * <tr>
	 * <td>星期天</td>
	 * <td>星期一</td>
	 * <td>星期二</td>
	 * <td>星期三</td>
	 * <td>星期四</td>
	 * <td>星期五</td>
	 * <td>星期六</td>
	 * </tr>
	 * <tr>
	 * <td>1<span>这里放参数</span></td>
	 * <td>2</td>
	 * <td>3<span>这里放参数</span></td>
	 * <td>4</td>
	 * <td>5</td>
	 * <td>6<span>这里放参数</span></td>
	 * <td>7</td>
	 * </tr>
	 * <tr>
	 * <td>8</td>
	 * <td>9</td>
	 * <td>10</td>
	 * <td>11</td>
	 * <td>12</td>
	 * <td>13</td>
	 * <td>14</td>
	 * </tr>
	 * <tr>
	 * <td>15</td>
	 * <td>16</td>
	 * <td>17</td>
	 * <td>18</td>
	 * <td>19</td>
	 * <td>20</td>
	 * <td>21</td>
	 * </tr>
	 * <tr>
	 * <td>22</td>
	 * <td>23</td>
	 * <td>24</td>
	 * <td>25</td>
	 * <td>26</td>
	 * <td>27</td>
	 * <td>28</td>
	 * </tr>
	 * <tr>
	 * <td>29</td>
	 * <td>30</td>
	 * <td>31</td>
	 * <td>&nbsp;</td>
	 * <td>&nbsp;</td>
	 * <td>&nbsp;</td>
	 * <td>&nbsp;</td>
	 * </tr>
	 * </table>
	 * 
	 * @param sdate
	 *            日期(yyyy-MM)
	 * @param needTable
	 *            是否需要表格
	 * @param params
	 *            要指定日中要显示的参数key:日
	 * @return 如果needTable为true，则返回表格，如果为false只返回日期行
	 */
	public static String calendarTable(String sdate, boolean needTable, Map<Integer, String> params) {
		Date date = DateUtil.parseDate(sdate, "yyyy-MM");
		int lastDay = DateUtil.getMontyLastDay(date);

		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.set(Calendar.DATE, 1);
		int sweek = DateUtil.getWeek(cal.getTime());

		cal.set(Calendar.DATE, lastDay);
		int eweek = DateUtil.getWeek(cal.getTime());

		String nt = "\n\t";

		StringBuffer buff = new StringBuffer();
		if (needTable) {
			buff.append("<table border='1'>").append(nt);
			buff.append("<tr>").append(nt);
			buff.append("<td>星期天</td>").append(nt);
			buff.append("<td>星期一</td>").append(nt);
			buff.append("<td>星期二</td>").append(nt);
			buff.append("<td>星期三</td>").append(nt);
			buff.append("<td>星期四</td>").append(nt);
			buff.append("<td>星期五</td>").append(nt);
			buff.append("<td>星期六</td>").append(nt);
			buff.append("</tr>").append(nt);
		}

		for (int i = 1; i <= lastDay; i++) {
			// 控制道行
			if (i == 1) {
				buff.append("<tr>").append(nt);
				if (sweek != 7) {
					for (int sw = 0; sw < sweek; sw++) {
						buff.append("<td>&nbsp;</td>").append(nt);
					}
				}
			}

			String content = "";
			if (params != null && !params.isEmpty()) {
				content = params.get(i);
				content = content == null ? "" : "<p>" + content + "</p>";
			}

			// 中间日期部份
			buff.append("<td>").append(i).append(content).append("</td>").append(nt);
			if ((sweek + i) % 7 == 0) {
				buff.append("</tr>").append(nt);
				buff.append("<tr>").append(nt);
			}

			// 控制最后一行
			if (i == lastDay) {
				if (eweek != 6) {
					int temp = 6 - ((eweek == 7) ? 0 : eweek);
					while (temp > 0) {
						buff.append("<td>&nbsp;</td>").append(nt);
						temp--;
					}
				}
				buff.append("</tr>");
			}
		}
		if (needTable) {
			buff.append("\r</table>");
		}
		return buff.toString();
	}

	/**
	 * 得到日期的上一天的日期
	 * 
	 * @param date
	 *            如果为空，取当时日期
	 * @return
	 */
	public static Date getPrvDayDate(Date date) {
		Calendar calendar = Calendar.getInstance();
		if (date != null) {
			calendar.setTime(date);
		}
		calendar.add(Calendar.DAY_OF_MONTH, -1);
		return calendar.getTime();
	}

	/**
	 * 得到日期的上一小时的日期
	 * 
	 * @param date
	 *            如果为空，取当时日期
	 * @return
	 */
	public static Date getPrvHourDate(Date date) {
		Calendar calendar = Calendar.getInstance();
		if (date != null) {
			calendar.setTime(date);
		}
		calendar.add(Calendar.HOUR_OF_DAY, -1);
		return calendar.getTime();
	}

	/**
	 * 得到日期的下一天的日期
	 * 
	 * @param date
	 *            如果为空，取当时日期
	 * @return
	 */
	public static Date getNextDayDate(Date date) {
		Calendar calendar = Calendar.getInstance();
		if (date != null) {
			calendar.setTime(date);
		}
		calendar.add(Calendar.DAY_OF_MONTH, 1);
		return calendar.getTime();
	}

	/**
	 * 将一个(yyyyMMddHHmmss)格式化
	 * 
	 * @param date
	 *            日期(可选)
	 * @param pattern
	 *            返回格式，可选
	 * @return pattern指定格式，如果为空返回 yyyy-MM-dd HH:mm:ss
	 */
	public static String parseFullDate(String date, String pattern) {
		if (date == null) {
			return formatDate(YYYY_MM_DD_HH_MM_SS);
		}
		while (date.length() < 14) {
			date += "0";
		}
		return formatDate(parseDate(date, YYYYMMDDHHMMSS), pattern == null ? YYYY_MM_DD_HH_MM_SS : pattern);
	}

	/**
	 * 将一个(yyyyMMddHHmmss)格式化
	 * 
	 * @param date
	 *            (可选)
	 * @return yyyy-MM-dd HH:mm:ss
	 */
	public static String parseFullDate(String date) {
		if (date == null || "".equals(date)) {
			return formatDate(YYYY_MM_DD_HH_MM_SS);
		}
		while (date.length() < 14) {
			date += "0";
		}
		return formatDate(parseDate(date, YYYYMMDDHHMMSS), YYYY_MM_DD_HH_MM_SS);
	}

	/**
	 * 返回年龄
	 * 
	 * @param date
	 * @return
	 */
	public static int getAge(Date date) {
		if (date == null){
			return 0;
		}
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int _year = getYear(c);
		int _month = getMonth(c);
		int _date = getDate(c);

		Calendar cN = Calendar.getInstance();
		int yN = getYear(cN);
		int mN = getMonth(cN);
		int dN = getDate(cN);

		if (_year >= yN){
			return 0;
		}

		else if (_month > mN){
			return yN - _year;
		}
		else if (_month < mN){
			return yN - _year - 1;
		}

		else if (_date >= dN){
			return yN - _year;
		}

		else{
			return yN - _year - 1;
		}
	}

	/**
	 * 获取下周一时间(周一为一周的开始)

	 */
	public static Date getNextMonday() throws Exception {
		Calendar cal = Calendar.getInstance();
		int week = cal.get(Calendar.DAY_OF_WEEK);
		if (week > 1) {
			cal.add(Calendar.DAY_OF_MONTH, -(week - 2) + 7);
		} else {
			cal.add(Calendar.DAY_OF_MONTH, 1);
		}
		return cal.getTime();
	}

	/**
	 * 获取这周一时间
	 * 
	 * @return
	 * @throws Exception
	 */
	public static Date getMonday() throws Exception {
		Calendar cal = Calendar.getInstance();
		int week = cal.get(Calendar.DAY_OF_WEEK);
		if (week > 1) {
			cal.add(Calendar.DAY_OF_MONTH, -(week - 2));
		} else {
			cal.add(Calendar.DAY_OF_MONTH, -6);
		}
		return cal.getTime();
	}

	/**
	 * 获取描述时间
	 */
	public static String getDescribDate(long datetime) {
		String des = "";
		Date date = new Date(datetime);
		Calendar c = Calendar.getInstance();
		c.setTime(date);

		if (isToday(formatDate(date, DateUtil.YYYY_MM_DD))) {
			des += "今日";
		} else {
			des += DateUtil.getDate(c) + "日";
		}

		des += DateUtil.formatDate(date, "HH:mm");

		return des;
	}

	static Logger logger = LoggerFactory.getLogger(DateUtil.class);
	private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
	private static final String DATE_FORMATTION = "yyyyMMddHHmmss";
	private static final String DATE_SHORT_FORMAT = "yyyy-MM-dd";
	private static final String DATE_SHORT_FORMATTION = "yyyyMMdd";
	private static final String DATE_SHORT_FORMAT_YEAR = "yyyy";
	private static final String DATE_SHORT_FORMAT_MONTH = "yyyy-MM";
	private static final String DATE_MONTH_DAY_FORMAT = "MM-dd";

	/**
	 * 标准时间格式转化为字符串
	 */
	public static String date2String(Date date, String format) {
		String dateStr = "";
		try {
			if (date != null) {
				dateStr = new SimpleDateFormat(format).format(date.getTime());
			}
		} catch (Exception e) {
			logger.error("日期转化为字符串出错！");
			e.printStackTrace();
		}
		return dateStr;
	}

	/**
	 * 字符串转化为时间格式
	 * 
	 * @param dateStr
	 *            日期字符串
	 * @return Date 日期
	 */
	public static Date string2Date(String dateStr, String format) {
		Date date = null;
		if (dateStr != null && !("").equals(dateStr)) {
			try {
				date = new SimpleDateFormat(format).parse(dateStr);
			} catch (ParseException e) {
				logger.error("字符串转化为日期出错！");
				e.printStackTrace();
			}
		}
		return date;
	}

	public static Date String2Date(String dateStr, String format, Locale locale, TimeZone timezone) {
		Date date = null;
		SimpleDateFormat sdf;
		try {
			if (locale != null) {
				sdf = new SimpleDateFormat(format, locale);
			} else {
				sdf = new SimpleDateFormat(format);
			}

			if (timezone != null) {
				sdf.setTimeZone(timezone);
			}

			sdf.parse(dateStr);
		} catch (ParseException e) {
			logger.error("字符串转化为日期出错！");
			e.printStackTrace();
		}
		return date;
	}

	/**
	 * 将日期字符串转成固定8位的日期格式，如2016-1-1转成2016-01-01
	 * 
	 * @Description TODO
	 * @param dateStr
	 * @return
	 */
	public static String dateStringFormart10(String dateStr) {
		if (StringUtils.isBlank(dateStr)){
			return null;
		}
		StringBuilder target = new StringBuilder();
		String[] dds = dateStr.split("-");
		target.append(dds[0]).append("-");
		target.append(dds[1].length() < 2 ? "0" + dds[1] : dds[1]);
		target.append("-").append(dds[2].length() < 2 ? "0" + dds[2] : dds[2]);
		return target.toString();

	}

	public static boolean isYesterday(Date a) {
		Calendar c = Calendar.getInstance();
		c.set(Calendar.DATE, c.get(Calendar.DATE) - 1);
		Date today = c.getTime();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		return format.format(today).equals(format.format(a));
	}

	public static boolean isToday(Date a) {
		Date today = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		return format.format(today).equals(format.format(a));
	}

	/**
	 * 标准时间格式转化为字符串
	 */
	public static String date2String(Date date) {
		String dateStr = "";
		try {
			if (date != null) {
				dateStr = new SimpleDateFormat(DATE_FORMAT).format(date.getTime());
			}
		} catch (Exception e) {
			logger.error("日期转化为字符串出错！");
			e.printStackTrace();
		}
		return dateStr;
	}

	/**
	 * 短时间格式转化为字符串
	 * 
	 * @param date
	 *            日期
	 * @return String 日期字符串
	 */
	public static String dateShort2String(Date date) {
		String dateStr = "";
		try {
			if (date != null) {
				dateStr = new SimpleDateFormat(DATE_SHORT_FORMAT).format(date.getTime());
			}
		} catch (Exception e) {
			logger.error("日期转化为字符串出错！");
			e.printStackTrace();
		}
		return dateStr;
	}

	/**
	 * 短时间格式转化为字符串
	 * 
	 * @param date
	 *            日期
	 * @return String 日期字符串
	 */
	public static String datesShort2String(Date date) {
		String dateStr = "";
		try {
			if (date != null) {
				dateStr = new SimpleDateFormat(DATE_SHORT_FORMATTION).format(date.getTime());
			}
		} catch (Exception e) {
			logger.error("日期转化为字符串出错！");
			e.printStackTrace();
		}
		return dateStr;
	}

	/**
	 * 短时间格式转化为字符串

	 */
	public static String dateShort2String(Long time) {
		String dateStr = "";
		try {
			if (time != null) {
				dateStr = new SimpleDateFormat(DATE_SHORT_FORMAT).format(time);
			}
		} catch (Exception e) {
			logger.error("日期转化为字符串出错！");
			e.printStackTrace();
		}
		return dateStr;
	}

	/**
	 * 字符串转化为短时间格式
	 * 
	 * @param dateStr
	 *            日期字符串
	 * @return Date 日期
	 */
	public static Date string2DateShort(String dateStr) {
		Date date = null;
		if (dateStr != null && !("").equals(dateStr)) {
			try {
				date = new SimpleDateFormat(DATE_SHORT_FORMAT).parse(dateStr);
			} catch (ParseException e) {
				logger.error("字符串转化为日期出错！");
				e.printStackTrace();
			}
		}
		return date;
	}

	/**
	 * 月日时间格式转化为字符串
	 * 
	 * @param date
	 *            日期
	 * @return String 日期字符串 yyyyMMddHHmmss
	 */
	public static String dates2String(Date date) {
		String dateStr = "";
		try {
			if (date != null) {
				dateStr = new SimpleDateFormat(DATE_FORMATTION).format(date.getTime());
			}
		} catch (Exception e) {
			logger.error("日期转化为字符串出错！");
			e.printStackTrace();
		}
		return dateStr;
	}

	/**
	 * 月日时间格式转化为字符串
	 * 
	 * @param date
	 *            日期
	 * @return String 日期字符串
	 */
	public static String dateMonthAndDay2String(Date date) {
		String dateStr = "";
		try {
			if (date != null) {
				dateStr = new SimpleDateFormat(DATE_MONTH_DAY_FORMAT).format(date.getTime());
			}
		} catch (Exception e) {
			logger.error("日期转化为字符串出错！");
			e.printStackTrace();
		}
		return dateStr;
	}

	/**
	 * 字符串转化为月日时间格式
	 * 
	 * @param dateStr
	 *            日期字符串
	 * @return Date 日期
	 */
	public static Date string2DateMonthAndDay(String dateStr) {
		Date date = null;
		if (dateStr != null && !("").equals(dateStr)) {
			try {
				date = new SimpleDateFormat(DATE_MONTH_DAY_FORMAT).parse(dateStr);
			} catch (ParseException e) {
				logger.error("字符串转化为日期出错！");
				e.printStackTrace();
			}
		}
		return date;
	}

	/**
	 * 年时间格式转化为字符串 yyyy
	 * 
	 * @param date
	 *            日期
	 * @return String 日期字符串 yyyy
	 */
	public static String date2YearString(Date date) {
		String dateStr = "";
		try {
			if (date != null) {
				dateStr = new SimpleDateFormat(DATE_SHORT_FORMAT_YEAR).format(date.getTime());
			}
		} catch (Exception e) {
			logger.error("日期转化为字符串出错！");
			e.printStackTrace();
		}
		return dateStr;
	}

	/**
	 * 年月时间格式转化为字符串 yyyy-MM
	 * 
	 * @param date
	 *            日期
	 * @return String 日期字符串 yyyy-MM
	 */
	public static String date2YearMonthString(Date date) {
		String dateStr = "";
		try {
			if (date != null) {
				dateStr = new SimpleDateFormat(DATE_SHORT_FORMAT_MONTH).format(date.getTime());
			}
		} catch (Exception e) {
			logger.error("日期转化为字符串出错！");
			e.printStackTrace();
		}
		return dateStr;
	}

	/**
	 * 年份的加减运算

	 */
	public static Date addOrMinusYear(Date nowDate, int i) {
		Date rtn = null;
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(nowDate);
		cal.add(1, i);
		rtn = cal.getTime();
		return rtn;
	}

	/**
	 * 月份的加减运算

	 */
	public static Date addOrMinusMonth(Date nowDate, int i) {
		Date rtn = null;
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(nowDate);
		cal.add(2, i);
		rtn = cal.getTime();
		return rtn;
	}

	public static String covertTime(long time) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		Date oldDate = new Date(time);
		String nowDateStr = df.format(date);
		String oldDateStr = df.format(oldDate);
		long nowTime = date.getTime();
		long l = nowTime - time;
		StringBuffer timeStr = new StringBuffer();
		long day = l / (24 * 60 * 60 * 1000);
		long hour = l / (60 * 60 * 1000) - day * 24;
		long min = (l / (60 * 1000)) - day * 24 * 60 - hour * 60;
		if (nowDateStr.equals(oldDateStr)) {
			if (hour >= 1) {
				timeStr.append(hour).append("小时前");
			} else if (min >= 1) {
				timeStr.append(min).append("分钟前");
			} else if (min < 1) {
				timeStr.append("刚刚");
			}
		} else {
			int a = Integer.parseInt(nowDateStr.substring(8));
			int b = Integer.parseInt(oldDateStr.substring(8));
			int c = a - b;
			if (day <= 1 && c == 1) {
				timeStr.append("昨天");
			} else {
				int nowYear = Integer.parseInt(nowDateStr.substring(0, 4));
				int oldYear = Integer.parseInt(oldDateStr.substring(0, 4));
				if (nowYear - oldYear >= 1) {
					timeStr.append("一年前");
				} else {
					Calendar cal = Calendar.getInstance();
					cal.setTime(oldDate);
					int monthValue = cal.get(Calendar.MONTH) + 1;
					int dayValue = cal.get(Calendar.DAY_OF_MONTH);
					timeStr.append(monthValue).append("月").append(dayValue).append("日");
				}
			}
		}
		return timeStr.toString();
	}

	/**
	 * 计算2个日期之间有多少分钟
	 * 
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public static long minTimeBetween(Date startDate, Date endDate) {
		return (endDate.getTime() - startDate.getTime()) / (1000 * 60);
	}

	/**
	 * 获取时间差字符串 hh:mm:ss格式
	 * 
	 * @param diffSes
	 *            时间差的秒数
	 * @return
	 */
	public static String getDiffTimeForMaxHourStr(long diffSes) {
		long diffHour = diffSes / (60 * 60);
		String hours = "00";
		String mins = "00";
		String ses = "00";
		if (diffHour >= 1) {
			if (diffHour < 10) {
				hours = "0" + diffHour;
			} else {
				hours = String.valueOf(diffHour);
			}
			diffSes = diffSes - diffHour * 60 * 60;
		}

		long diffMin = diffSes / 60;
		if (diffMin >= 1) {
			if (diffMin < 10) {
				mins = "0" + diffMin;
			} else {
				mins = String.valueOf(diffMin);
			}
			diffSes = diffSes - diffMin * 60;
		}

		if (diffSes < 10) {
			ses = "0" + diffSes;
		} else {
			ses = String.valueOf(diffSes);
		}
		return hours + ":" + mins + ":" + ses;
	}

	/**
	 * 获取时间差字符串 hh:mm:ss格式
	 * 
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public static String getDiffTimeForMaxHourStr(Date startDate, Date endDate) {
		long diffSes = (endDate.getTime() - startDate.getTime()) / 1000;
		return getDiffTimeForMaxHourStr(diffSes);
	}

	/**
	 * 
	 * @Title: isAppointDay @Description: 判断是不是指定的那一天 @param: @param
	 *         day @param: @return @return: boolean @throws
	 */
	public static boolean isAppointDay(String day, Date apDay) {
		Date d, appointDay;
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		try {
			d = dateFormat.parse(day);
			appointDay = dateFormat.parse(dateFormat.format(apDay));
			return appointDay.compareTo(d) == 0 ? true : false;
		} catch (ParseException e) {
		}
		return false;
	}

	/**
	 * 
	 * @Title: getCurMonthDay @Description:
	 *         得到当月第一天以及最后一天 @param: @return @return: String @throws
	 */
	public static List<String> getCurMonthDay() {
		// 查询当月第一天以及最后一天
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		// 获取当前月第一天：
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, 0);
		c.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天
		String first = format.format(c.getTime());

		// 获取当前月最后一天
		Calendar ca = Calendar.getInstance();
		ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
		String last = format.format(ca.getTime());

		List<String> list = new ArrayList<String>();
		list.add(first);
		list.add(last);
		return list;
	}

	/**
	 * 
	 * @Title: getAgeByBirthday @Description: 根据生日计算年龄 @param: @param
	 *         birthday @param: @return @return: int @throws
	 */
	public static int getAgeByBirthday(Date birthday) {
		Calendar cal = Calendar.getInstance();

		if (cal.before(birthday)) {
			throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
		}

		int yearNow = cal.get(Calendar.YEAR);
		int monthNow = cal.get(Calendar.MONTH) + 1;
		int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);

		cal.setTime(birthday);
		int yearBirth = cal.get(Calendar.YEAR);
		int monthBirth = cal.get(Calendar.MONTH) + 1;
		int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

		int age = yearNow - yearBirth;

		if (monthNow <= monthBirth) {
			if (monthNow == monthBirth) {
				// monthNow==monthBirth
				if (dayOfMonthNow < dayOfMonthBirth) {
					age--;
				}
			} else {
				// monthNow>monthBirth
				age--;
			}
		}
		return age;
	}

	/**
	 * 
	 * @Title: getFirstAndLastDay @Description: 获取指定月份的第一天以及最后一天 @param: @param
	 *         datadate @param: @return @return: List<String> @throws
	 */
	public static List<String> getFirstAndLastDay(String datadate) {
		Date date = null;
		String day_last = null;
		String day_first = null;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			date = format.parse(datadate);
			// 创建日历
			Calendar ca = Calendar.getInstance();
			ca.setTime(date);
			ca.add(Calendar.MONTH, 1); // 加一个月
			ca.set(Calendar.DATE, 1); // 设置为该月第一天
			ca.add(Calendar.DATE, -1); // 再减一天即为上个月最后一天
			day_last = format.format(ca.getTime());

			// 创建日历
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.set(Calendar.DAY_OF_MONTH, 1);
			day_first = format.format(calendar.getTime());
			List<String> list = new ArrayList<String>();
			list.add(day_first);
			list.add(day_last);
			return list;
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static long min = 60;//一分钟等于60秒
	public static long hour = 60*min;//一个小时等于3600秒
	public static long day = 24*hour;//一天等于24*60*60秒
	public static long month = 30*day; //一个月30天
	public static long year = 365*day;//一年365天
	public static long[] smallToBig = new long[]{min,hour,day,month,year};
	public static String[] smallToBigText = new String[]{"分钟","小时","天","个月","年"};
	public static String suffix = "前";

	/**
	 *
	 * @param historyTime
	 * @return
	 */
	public static String getHistoryTimeDescription(Date historyTime){
		if(null==historyTime){
			return null;
		}
		long nowTime = System.currentTimeMillis();
		long diff = (nowTime-historyTime.getTime())/1000;//以秒为单位

		int length = smallToBig.length;
		int index = 0;
		for(int i=0;i<length;i++ ){
			if(diff<=smallToBig[i]){//若小于当前时间时，跳出循环
				index = i;
				break;
			}
			if(i==length-1){
				index=length;
			}
		}
		if(index<length&&diff==smallToBig[index]){
			return 1+smallToBigText[index]+suffix;
		}else if(index==0){
			return diff+"秒"+suffix;
		}
		return (diff/smallToBig[index-1])+smallToBigText[index-1]+suffix;

	}
}
